<template>
  <!-- 电控-充值记录 -->
  <div class="swipe_details">
    <!-- <el-form :inline="true" :model="elform">
      <el-form-item label="用户名">
        <el-input v-model="userName" placeholder="名称" size="mini" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="phoneNumber" placeholder="手机号" size="mini" clearable></el-input>
      </el-form-item>
      <el-form-item label="卡类型">
        <el-select v-model="cardtypes" placeholder="请选择" size="mini" clearable>
          <el-option label="全部类型" value></el-option>
          <el-option
            v-for="item in cardtypesoption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form> -->
    <el-form :inline="true" :model="elform" class="demo-form-inline1">
       <el-form-item label="开始日期:">
        <el-date-picker
          v-model="datetime[0]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[0]"
          value-format="HH:mm:ss"
          placeholder="开始时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>
      <el-form-item label="结束日期:">
        <el-date-picker
          v-model="datetime[1]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="结束日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[1]"
          value-format="HH:mm:ss"
          placeholder="结束时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>
      <el-form-item class="searchmarigin">
        <el-button
          type="primary"
          @click="onSubmit"
          size="mini"
          icon="el-icon-search"
          >查询</el-button
        >
        <el-button
          type="primary"
          @click="onExport"
          size="mini"
          icon="el-icon-document-copy"
          >导出</el-button
        >
        <el-button
          type="primary"
          @click="onExport('print')"
          size="mini"
          icon="el-icon-document-copy"
          >打印</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-popover width="500" placement="top" trigger="click">
          <el-row>
            <el-col
              :span="6"
              v-for="item in Object.keys(formThead)"
              :key="item"
            >
              <el-checkbox
                :label="formThead[item].label"
                v-model="formThead[item].checked"
                @change="checkboxChanged()"
              ></el-checkbox>
            </el-col>
          </el-row>
          <el-button
            slot="reference"
            size="mini"
            type="primary"
            icon="el-icon-edit-outline"
            >自定义</el-button
          >
        </el-popover>
      </el-form-item>
    </el-form>
    <div class="tablemain">
      <el-table
        v-loading="loading"
        :data="detailslist"
        ref="table"
        border
        highlight-current-row
        style="width: 100%"
        :header-cell-style="headFirst"
        :cell-style="(res) => headFirst_col(res, [])"
      >
        <el-table-column
          prop="userName"
          label="姓名"
          v-if="formThead.userName.checked"
        ></el-table-column>
        <el-table-column
          prop="departmentName"
          label="部门"
          v-if="formThead.departmentName.checked"
        ></el-table-column>
        <el-table-column
          prop="terminalName"
          label="设备名称"
          v-if="formThead.terminalName.checked"
        ></el-table-column>
        <el-table-column
          prop="rechargeBalance"
          label="充值金额(元)"
          v-if="formThead.rechargeBalance.checked"
          min-width="120px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.rechargeBalance | amountyuan }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="newBalance"
          label="充值后余额(元)"
          v-if="formThead.newBalance.checked"
          min-width="120px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.newBalance | amountyuan }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="adjustType"
          label="调整类型"
          v-if="formThead.adjustType.checked"
          min-width="120px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.adjustType | fileteradjustType }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="rechargeState"
          label="充值状态"
          v-if="formThead.rechargeState.checked"
          min-width="120px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.rechargeState | rechargeStateType }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="rechargeTime"
          label="充值时间"
          v-if="formThead.rechargeTime.checked"
          min-width="160px"
        ></el-table-column>
        <el-table-column
          prop="successTime"
          label="到账时间"
          v-if="formThead.successTime.checked"
          min-width="160px"
        ></el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangepage"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordCount"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      filename: "电控充值记录",
      // 用户id
      userGuid: "",
      // 自己输入的房间号
      phoneNumber: "",
      departmentInfo: [],
      departmentGuid: "",
      groupingoption: [],
      groupingGuid: "",
      userName: "",
      datetime: [],
      time:[],
      cardtypes: "",
      // 类型列表
      cardtypesoption: [
        {
          label: "A卡",
          value: 1,
        },
        {
          label: "B卡",
          value: 2,
        },
        {
          label: "身份证UID",
          value: 3,
        },
        {
          label: "CPU学生卡",
          value: 4,
        },
      ],
      elform: {},
      formThead: {
        userName: {
          label: "姓名",
          prop: "userName",
          checked: true,
        },
        departmentName: {
          label: "部门",
          prop: "departmentName",
          checked: true,
        },
        terminalName: {
          label: "设备名称",
          prop: "terminalName",
          checked: true,
        },
        rechargeBalance: {
          label: "充值金额(元)",
          prop: "rechargeBalance",
          checked: true,
        },
        newBalance: {
          label: "充值后余额",
          prop: "newBalance",
          checked: true,
        },
        adjustType: {
          label: "调整类型",
          prop: "adjustType",
          checked: true,
        },
        rechargeState: {
          label: "充值状态",
          prop: "rechargeState",
          checked: true,
        },
        rechargeTime: {
          label: "充值时间",
          prop: "rechargeTime",
          checked: true,
        },
        successTime: {
          label: "到账时间",
          prop: "successTime",
          checked: true,
        },
      },
      detailslist: [],
      loading: false,
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      //导出数据
      detailslistExportlist: [],
      //汇总合计
      totalto: false,
    };
  },
  props: ["roomGuid"],
  filters: {
    rechargeStateType(val) {
      val = Number(val);
      switch (val) {
        case 0:
          return "未到账";
          break;
        case 1:
          return "已到账";
          break;
        case 2:
          return "设备未找到";
          break;
        case 3:
          return "充值下发错误";
          break;
        case 5:
          return "5充值领取失败";
          break;
        default:
          return "";
          break;
      }
    },
  },
  created() {
    this.userGuid = sessionStorage.getItem("administrator");
    // 初始化时间
    this.datetime = [this.getNowTime('yy-mm-dd'), this.getNowTime('yy-mm-dd')]
    this.time = ['00:00:00', '23:59:59']
    console.log(this.userGuid);
  },
  mounted() {},
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid;
      },
    },
  },
  methods: {
    // 表格重新渲染
    checkboxChanged() {
      this.$nextTick(() => {
        this.$refs["table"].doLayout();
      });
    },
    // 点击查询后触发
    onSubmit() {
      this.pageNum = 1;
      let searchInfo = {};
      // 姓名  规则
      if (this.userName != "") {
        searchInfo.userName = this.userName;
      }
      // 日期限定
      if (this.datetime != null) {
        if (this.datetime.length != 0) {
              searchInfo.startTime = this.datetime[0] + ' ' + this.time[0]
          searchInfo.endTime = this.datetime[1] + ' ' + this.time[1]
        }
      }
      // 类型限定
      if (this.cardtypes != "") {
        searchInfo.cardType = this.cardtypes;
      }
      // 手机号限定
      if (this.phoneNumber != "") {
        searchInfo.phoneNumber = this.phoneNumber;
      }
      searchInfo.unitGuid = this.changeschoolid;
      this.searchInfo = searchInfo;
      this.getList();
    },
    getList() {
      this.loading = true;
      this.$http({
        url: this.$http.adornUrl("/terminal/electric/electric-recharge-page"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            asc: true,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo,
          },
          messageType: 0,
        }),
      }).then(({ data }) => {
        this.loading = false;
        if (data.messageCode == 200) {
          this.recordCount = data.messageContent.recordCount;
          this.pageNum = data.messageContent.pageNum;
          this.currentPage = data.messageContent.pageNum;
          this.detailslist = data.messageContent.data || [];
          if (this.detailslist.length == 0) {
            this.$message({
              message: "查询成功当前暂无数据",
              type: "success",
            });
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    // 导出数据
    async onExport(type) {
      if (this.recordCount == 0) {
        this.$message({
          message: "请查询数据后,在进行此操作",
          type: "warning",
        });
        return false;
      }
      await this.getExeclDate();
      if (type == "print") {
        this.printJS();
      } else {
        this.export2Excel();
      }
    },
    getExeclDate() {
      let _this = this;
      return new Promise(function (resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              "/terminal/electric/electric-recharge-page"
            ),
            method: "post",
            data: _this.$http.adornData({
              messageContent: {
                asc: true,
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo,
              },
              messageType: 0,
            }),
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              // _this.export2Excel(data.messageContent.data);
              _this.detailslistExportlist = data.messageContent.data || [];
              _this.detailslistExportlist.map((item) => {
                item.rechargeBalance = _this.$options.filters.amountyuan(
                  item.rechargeBalance
                );
                item.newBalance = _this.$options.filters.amountyuan(
                  item.newBalance
                );
                item.adjustType = _this.$options.filters.fileteradjustType(
                  item.adjustType
                );
                item.rechargeState = _this.$options.filters.rechargeStateType(
                  item.rechargeState
                );
              });
              resolve(_this.detailslistExportlist);
            } else {
              _this.$message.error(data.errorMessage);
              reject(data.errorMessage);
            }
          });
      });
    },
    // 打印相关
    printJS() {
      let someJSONdata = this.detailslistExportlist;
      const title = "电控充值记录表";
      this.unitName = sessionStorage.getItem("unitName");
      this.loginName = sessionStorage.getItem("username");
      const properties = [];
      // 拿到数据formThead
      for (let key in this.formThead) {
        if (this.formThead[key].checked) {
          if (key == "rechargeTime" || key == "successTime") {
            properties.push({
              displayName: this.formThead[key].label,
              field: this.formThead[key].prop,
              columnSize: 130 / (Object.keys(this.formThead).length + 2) + "%",
            });
          } else {
            properties.push({
              displayName: this.formThead[key].label,
              field: this.formThead[key].prop,
              columnSize: 100 / (Object.keys(this.formThead).length + 2) + "%",
            });
          }
        }
      }
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            "yyyy-MM-dd"
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            "yyyy-MM-dd"
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: "json",
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 2,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          this.loginName,
          this.getNowTime("yy-mm-dd hh:mm:ss")
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle(),
      });
    },
    // 通行记录导出方法
    export2Excel() {
      const nowtime = this.getimeto();
      require.ensure([], () => {
        const multiHeader = [];
        const multiHeader2 = [];
        const merges = [];
        const { export_json_to_excel } = require("../../excel/Export2Excel");
        let tHeader = [];
        let filterVal = [];
        for (let key in this.formThead) {
          if (this.formThead[key].checked) {
            tHeader.push(this.formThead[key].label);
            filterVal.push(this.formThead[key].prop);
          }
        }
        const list = this.detailslistExportlist;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime,
        });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChangepage(val) {
      this.pageNum = val;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.swipe_details {
  padding: 10px;
  .el-table__row .el-table__row--level-1 {
    background-color: #e5e9f2;
  }
  .el-form-item {
    margin-bottom: 0px;
  }
  .inpWidth {
    width: 120px;
  }
  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
   //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
}
</style>